/*!
 * <File comment goes here!!>
 * 
 * Copyright (c) 2008 by <Quang Huy / NTU>
 */

#include "CvrPara.h"
#include "../CVR/svmtrain.h"
#include "../CVR/svmpredict.h"
#include <ctime>

CvrPara::CvrPara( int nDimensions ):ObjectiveFunction( -1, nDimensions, 0, 0.6)
{
}

CvrPara::CvrPara( int nDimensions, double lowerBound, double upperBound ):ObjectiveFunction( -1, nDimensions, lowerBound, upperBound)
{
}

CvrPara::CvrPara( int nDimensions, vector<double>& lowerBounds, vector<double>& upperBounds ):ObjectiveFunction( -1, nDimensions, lowerBounds, upperBounds)
{

}

CvrPara::~CvrPara()
{
}


double CvrPara::evaluate_( vector<double>& x )
{
	/*int i;
	double sum1, sum2;

	ObjectiveFunction::evaluate_( x );
	
	sum1 = 0.0;
	sum2 = 0.0;

	for(i=0; i<nDim; i++) {
		sum1 += ( x[ i ] * x[ i ] );
		sum2 += cos( 2 * PI * x[ i ] );
	}

	return -20 * exp( -0.2 * sqrt( sum1/nDim ) ) - exp( sum2/nDim ) + 20 + exp(1.0);*/
	
	char* trainFileName = "E:\\paper\\elevprogram\\gpowerload.txt";
	char* testFileName = "E:\\paper\\elevprogram\\gpowertest.txt";
	time_t now = time(0);
	char* ouptFileName = "E:\\paper\\elevprogram\\goutputdata.txt";
	char* modelFileName = "E:\\paper\\elevprogram\\gmodelFile.txt";

	svmtrain svmtrain;
	svmtrain.SetUpParameters(x[0],x[1]);
	svmtrain.train(trainFileName, modelFileName);
	svmpredict svmpredict;
	double predictRate = svmpredict.DoPredict(testFileName, ouptFileName, modelFileName);
	remove(ouptFileName);
	remove(modelFileName);
	
	//printf("Optimization Value: %.8g\n", x[0]);
	//printf("Predict Rate: %.8g\n", predictRate);
	//printf("Best Evaluation: %.8g\n", this->bestEvaluation());
	//printf("Best Solution: %.8g\n", this->bestSolution()[0]);

	return predictRate;
}

vector<double> CvrPara::gradient_( vector<double>& x )
{
	vector<double> grad(x.size(), 0.0);
	//<Manhtung>
	//Rewrite later//
	int i;
	double sum1 = 0, sum2 = 0;

	for(i=0; i<nDim; i++){
		sum1 += ( x[ i ] * x[ i ] );
		sum2 += cos( 2 * PI * x[ i ] );
	}

	for(i=0;i<nDim;i++){		
		if(sum1!=0)
        {
                grad[i] = -20 * exp( -0.2 * sqrt( sum1/nDim ) ) * ( -0.2 / sqrt( 1.0*nDim ) ) * ( 1/(2 * sqrt( sum1 )) ) * 2 * x[i]
                - exp( sum2 / nDim ) * ( 2 * acos( -1.0 ) / nDim ) * ( -sin ( 2 * acos( -1.0 ) * x[i] ) );
        }
        else
        {
                grad[i] = - exp( sum2 / nDim ) * ( 2 * acos( -1.0 ) / nDim ) * ( -sin ( 2 * acos( -1.0 ) * x[i] ) );
        }
	}
	//</Manhtung>

	return grad;
}